<template>
	<view class="container">
		<!-- 表单区域 -->
		<view class="form-content">
			<!-- 收缩压 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text class="text-black">收缩压</text>
				</view>
				<view class="input-wrapper" @tap="showSystolicPicker">
					<text :class="systolic !== '' ? 'selected-value' : 'placeholder'">{{ systolic !== '' ? systolic + ' mmHg' : '请选择收缩压' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 舒张压 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text class="text-black">舒张压</text>
				</view>
				<view class="input-wrapper" @tap="showDiastolicPicker">
					<text :class="diastolic !== '' ? 'selected-value' : 'placeholder'">{{ diastolic !== '' ? diastolic + ' mmHg' : '请选择舒张压' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 收缩压选择器 -->
			<uni-popup ref="sysPopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text @tap="hideSystolic" style="color: #c8cacf;">取消</text>
						<view class="title">
							<text class="selected-value text-blod" style="font-weight: 600;font-size: 34rpx;">收缩压 {{ tempSystolic }} mmHg</text>
						</view>
						<text @tap="confirmSystolic" style="color: #4cd080;">确定</text>
					</view>
					<view class="picker-content">
						<picker-view :value="[systolicRange.indexOf(tempSystolic)]" @change="onSystolicChange" class="picker-view">
							<picker-view-column>
								<view class="picker-item" v-for="item in systolicRange" :key="item">{{ item }}</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
			</uni-popup>

			<!-- 舒张压选择器 -->
			<uni-popup ref="diaPopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text @tap="hideDiastolic" style="color: #c8cacf;">取消</text>
						<view class="title">
							<text class="selected-value text-blod" style="font-weight: 600;font-size: 34rpx;">舒张压 {{ tempDiastolic }} mmHg</text>
						</view>
						<text @tap="confirmDiastolic" style="color: #4cd080;">确定</text>
					</view>
					<view class="picker-content">
						<picker-view :value="[diastolicRange.indexOf(tempDiastolic)]" @change="onDiastolicChange" class="picker-view">
							<picker-view-column>
								<view class="picker-item" v-for="item in diastolicRange" :key="item">{{ item }}</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
			</uni-popup>

			<!-- 测量类型 -->
			<!-- <view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text>测量类型:</text>
				</view>
				<view class="type-options">
					<view v-for="(type, index) in measurementTypes" :key="index" :class="['type-item', selectedType === type.value ? 'selected' : '']" @tap="selectType(type.value)">
						{{ type.label }}
					</view>
				</view>
			</view> -->

			<!-- 测量时间 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text class="text-black">测量时间</text>
				</view>
				<view class="input-wrapper" @tap="showTimePicker">
					<text :class="selectedTime ? 'selected-value' : 'placeholder'">{{ selectedTime || '请选择测量时间' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 时间选择器 -->
			<uni-popup ref="timePopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text @tap="hideTimePicker" style="color: #c8cacf;">取消</text>
						<view class="title">
							<text class="selected-value text-blod" style="font-weight: 600;font-size: 34rpx;">{{ formatTempTime }}</text>
						</view>
						<text @tap="confirmTimePicker" style="color: #4cd080;">确定</text>
					</view>
					<view class="picker-content">
						<picker-view :value="[yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex, secondIndex]" @change="onTimeChange" class="picker-view">
							<picker-view-column>
								<view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="day in days" :key="day">{{ day }}日</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="hour in hours" :key="hour">{{ hour.toString().padStart(2, '0') }}时</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="minute in minutes" :key="minute">{{ minute.toString().padStart(2, '0') }}分</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="second in seconds" :key="second">{{ second.toString().padStart(2, '0') }}秒</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
			</uni-popup>
		</view>

		<!-- 保存按钮 -->
		<view class="save-button" @tap="saveData">保存</view>
	</view>
</template>

<script>
import { mapGetters } from "vuex"
import { uniPopup } from '@dcloudio/uni-ui'
import { addBloodPressure, queryBloodPressureTypeList } from '@/api/healthData/everyBloodPressure.js'

export default {
	computed: mapGetters(['name', 'id']),
	components: { uniPopup },
	data() {
		return {
			measurementTypes: [],
			selectedType: 'empty',
			systolic: '',
			diastolic: '',
			tempSystolic: 120,
			tempDiastolic: 80,
			systolicRange: [],
			diastolicRange: [],
			selectedTime: '',
			tempTime: {
				year: new Date().getFullYear(),
				month: new Date().getMonth() + 1,
				day: new Date().getDate(),
				hour: new Date().getHours(),
				minute: new Date().getMinutes(),
				second: new Date().getSeconds()
			},
			years: [],
			months: Array.from({ length: 12 }, (_, i) => i + 1),
			days: Array.from({ length: 31 }, (_, i) => i + 1),
			hours: Array.from({ length: 24 }, (_, i) => i),
			minutes: Array.from({ length: 60 }, (_, i) => i),
			seconds: Array.from({ length: 60 }, (_, i) => i)
		}
	},
	onLoad(options) {
		this.targetId = options.targetId
		this.queryTypeList()
	},
	computed: {
		yearIndex() { return this.years.indexOf(this.tempTime.year) },
		monthIndex() { return this.months.indexOf(this.tempTime.month) },
		dayIndex() { return this.days.indexOf(this.tempTime.day) },
		hourIndex() { return this.hours.indexOf(this.tempTime.hour) },
		minuteIndex() { return this.minutes.indexOf(this.tempTime.minute) },
		secondIndex() { return this.seconds.indexOf(this.tempTime.second) },
		formatTempTime() {
			const { year, month, day, hour, minute, second } = this.tempTime
			const period = hour < 12 ? '上午' : '下午'
			const displayHour = hour % 12 || 12
			return `${period} ${displayHour}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`
		},
		formatSaveTime() {
			const { year, month, day, hour, minute, second } = this.tempTime
			return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`
		}
	},
	created() {
		// 年份范围
		const currentYear = new Date().getFullYear()
		for (let i = currentYear - 5; i <= currentYear + 5; i++) {
			this.years.push(i)
		}
		// 取值范围：高压 70-230、低压 40-140
		for (let i = 70; i <= 230; i++) this.systolicRange.push(i)
		for (let i = 40; i <= 140; i++) this.diastolicRange.push(i)
	},
	methods: {
		showSystolicPicker() { this.$refs.sysPopup.open() },
		hideSystolic() { this.$refs.sysPopup.close() },
		onSystolicChange(e) { const [idx] = e.detail.value; this.tempSystolic = this.systolicRange[idx] },
		confirmSystolic() { this.systolic = this.tempSystolic; this.hideSystolic() },

		showDiastolicPicker() { this.$refs.diaPopup.open() },
		hideDiastolic() { this.$refs.diaPopup.close() },
		onDiastolicChange(e) { const [idx] = e.detail.value; this.tempDiastolic = this.diastolicRange[idx] },
		confirmDiastolic() { this.diastolic = this.tempDiastolic; this.hideDiastolic() },

		selectType(type) { this.selectedType = type },
		showTimePicker() {
			if (!this.selectedTime) {
				const now = new Date()
				this.tempTime = { year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate(), hour: now.getHours(), minute: now.getMinutes(), second: now.getSeconds() }
			}
			this.$refs.timePopup.open()
		},
		hideTimePicker() { this.$refs.timePopup.close() },
		onTimeChange(e) {
			const [y, m, d, h, mi, s] = e.detail.value
			this.tempTime = { year: this.years[y], month: this.months[m], day: this.days[d], hour: this.hours[h], minute: this.minutes[mi], second: this.seconds[s] }
		},
		confirmTimePicker() { this.selectedTime = this.formatTempTime; this.hideTimePicker() },
		saveData() {
			if (this.systolic === '' || this.diastolic === '') {
				uni.showToast({ title: '请选择血压值', icon: 'none' });
				return;
			}
			if (!this.selectedTime) {
				uni.showToast({ title: '请选择测量时间', icon: 'none' });
				return;
			}
			const data = {}
			data.measuredTime = this.formatSaveTime
			data.systolicPressure = this.systolic
			data.diastolicPressure = this.diastolic
			data.sourceType = '1'
			data.sourceName = '手工录入'
			data.measuredType = this.selectedType
			data.userId = this.id
			addBloodPressure(data).then(res => {
				const measuredTypeName = this.measurementTypes.find(type => type.value === this.selectedType)?.label || '未知类型'
				uni.navigateTo({
					url: `/subPackage_1/pages/index/healthData/blood-pressure-success?systolic=${encodeURIComponent(this.systolic)}&diastolic=${encodeURIComponent(this.diastolic)}&measuredTime=${encodeURIComponent(this.selectedTime)}&measuredTypeName=${encodeURIComponent(measuredTypeName)}&id=${res.data}`
				})
			})
		},
		queryTypeList() {
			queryBloodPressureTypeList({ targetId: this.targetId }).then(res => { this.measurementTypes = res.data || [] })
		}
	}
}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #fff;
		padding-top: 20px;
	}
	.form-content { background-color: #fff; padding: 0 30rpx; }
	.form-item { padding: 30rpx 0; display: flex; align-items: center; justify-content: space-between; background-color: #fbfbfd; margin-bottom: 20rpx; border-radius: 10rpx; }
	.label { display: flex; align-items: center; gap: 10rpx; padding-left: 20rpx; }
	.required { color: #ff4d4f; margin-right: 6rpx; }
	.placeholder { color: #c8cacf; }
	.selected-value { color: #333; font-weight: 600; }
	.input-wrapper { flex: 1; display: flex; align-items: center; justify-content: flex-end; padding: 0 20rpx; }
	.arrow { color: #c8cacf; }
	.type-options { display: flex; flex-wrap: wrap; gap: 16rpx; padding: 0 20rpx 10rpx 20rpx; }
	.type-item { background-color: #fff; color: #666; padding: 14rpx 22rpx; border-radius: 100rpx; border: 1rpx solid #eee; }
	.type-item.selected { color: #4cd080; border-color: #4cd080; background: #eafff6; }
	.picker-container { background: #fff; border-top-left-radius: 16rpx; border-top-right-radius: 16rpx; }
	.picker-header { display: flex; align-items: center; justify-content: space-between; padding: 22rpx 30rpx; }
	.picker-content { height: 460rpx; }
	.picker-view { width: 100%; height: 100%; }
	.picker-item { height: 80rpx; line-height: 80rpx; text-align: center; }
	.save-button { position: fixed; left: 30rpx; right: 30rpx; bottom: 40rpx; height: 90rpx; background-color: #4cd080; color: #fff; border-radius: 100rpx; text-align: center; line-height: 90rpx; font-weight: 600; }
</style>


